import router from '../router';
import { clearStorage, getStorage } from '@/utils/cache';
import NProgress from 'nprogress';
import useSystemStore from '@/store/system';
import useUserStore from '@/store/user';

NProgress.configure({ showSpinner: false });

router.beforeEach(async (to, _, next) => {
  NProgress.start();
  if (getStorage('token')) {
    const sysStore = useSystemStore();
    const user = useUserStore();
    const { info } = user;
    try {
      if (!info) await user.getUserInfo();
      if (to.path === '/login') {
        next({ path: '/' });
      } else {
        if (sysStore.menus) {
          next();
        } else {
          const menus = await sysStore.genMenus();
          // 动态写入路由
          for (const oe of menus) router.addRoute(oe);
          next({ ...to, replace: true });
        }
      }
    } catch (error) {
      clearStorage();
      next('/401');
      console.error(error);
    }
  } else {
    /* has no token*/
    // 免登录直接进入
    if (to.meta.loginIngore) {
      next();
    } else {
      next('/login'); // 否则全部重定向到登录页
    }
  }
});

router.afterEach(NProgress.done);
